import { formatePrice } from '../../utils'
const state = {
    cartProducts: JSON.parse(window.localStorage.getItem('cart-products')) || []
}

const getters = {
    totalCount(state) {
        return state.cartProducts.reduce((sum, prod) => sum + prod.count, 0)
    },
    totalPrice(state) {
        return state.cartProducts.reduce((sum, prod) => formatePrice(sum + prod.totalPrice), 0)
    },
    checkedCount(state) {
        return state.cartProducts.reduce((sum, prod) => {
            if (prod.isChecked) {
                sum += prod.count
            }
            return sum
        }, 0)
    },
    checkedPrice(state) {
        return state.cartProducts.reduce((sum, prod) => {
            if (prod.isChecked) {
                sum += prod.totalPrice
            }
            return formatePrice(sum)
        }, 0)
    }
}
const mutations = {
    addToCart(state, product) {
        const prod = state.cartProducts.find(item => item.id === product.id)
        if (prod) {
            prod.count++
            prod.isChecked = true
            prod.totalPrice = prod.count * prod.price
        } else {
            state.cartProducts.push({
                ...product,
                count: 1,
                isChecked: true,
                totalPrice: product.price
            })
        }
    },
    deleteFromCart(state, prodId) {
        const _index = state.cartProducts.findIndex(item => item.id === prodId)
        _index !== -1 && state.cartProducts.splice(_index, 1)
    },
    updateProdNum(state,{
        prodId,
        count
    }) {
        const prod = state.cartProducts.find(item => item.id === prodId)
        if (prod) {
            prod.count = count
            prod.totalPrice = formatePrice(prod.price * count)
        }
    },
    updateChecked(state,{
        prodId,
        checked
    }) {
        const prod = state.cartProducts.find(item => item.id === prodId)
        prod && (prod.isChecked = checked)
    },
    updateAllChecked(state, checked) {
        state.cartProducts.forEach(prod => {
            prod.isChecked = checked
        })
    }
}
const actions = {}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}